import { useState, useEffect, useRef } from "react";
import { Button, Modal, Form, Switch, Card, Input } from "antd";
import { CloseOutlined, SearchOutlined } from "@ant-design/icons";
import classnames from "classnames";
import styles from "./index.less";
import { getOrgStaff } from "./service";
import Tree from "./Tree";
import Staff from "./Staff";
interface StaffInfo {
  orgName: string;
  userId: number;
  zhName: string;
}

const tabListNoTitle = [
  {
    key: 'org',
    tab: '组织机构',
  },
  {
    key: 'staff',
    tab: '成员'
  }
];
const OrgStaff = (props: { multiple: boolean,onSelectChange:Function }) => {
  // const treeRef = useRef();
  const [visible, setVisible] = useState(false);
  const [orgTree, setOrgtree] = useState<any[]>([]);
  const [searchValue, setSearchValue] = useState('');
  const [deleteKeys, setDeleteKeys] = useState(0);
  const [selectOrgKeys, setSelectOrgKeys] = useState<number[]>([]);
  const [checkedInfo, setCheckedInfo] = useState<StaffInfo[]>([]);
  const [tabActive, setTabActive] = useState('org');
  const [okSelected, setOkSelected] = useState<StaffInfo[]>([]);

  const _getOrgStaff = async () => {
    const res = await getOrgStaff();
    let formatRes = JSON.stringify(res.data);
    formatRes = formatRes.replaceAll('orgId', 'key')
      .replaceAll('orgName', 'title')
      .replaceAll('subList', 'children');
    setOrgtree([JSON.parse(formatRes)])
  }
  const onSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target;
    setSearchValue(value);
  }
  useEffect(() => {
    _getOrgStaff()
  }, [])
  useEffect(() => {
    if (visible) {
      setCheckedInfo(okSelected);
    }
  }, [visible])
  return (
    <div>
      {!okSelected.length ? <Button type='dashed' onClick={() => setVisible(true)}>
        人员列表
      </Button> : <div onClick={() => setVisible(true)} className={styles.showItem}>
        {
          okSelected.map(item => (
            <div key={item.userId} className={styles.selectItem}>
              <div className={styles.avatar}>{item.zhName[0]}</div>
              {item.zhName}
            </div>
          ))
        }
      </div>}
      <Modal
        title="成员列表"
        width={800}
        visible={visible}
        maskClosable={false}
        destroyOnClose
        onCancel={() => {
          setSelectOrgKeys([])
          setVisible(false)
        }}
        // destroyOnClose
        onOk={() => {
          // const data = (treeRef.current as any).onOk();
          // console.log(checkedInfo)
          props.onSelectChange(checkedInfo);
          setOkSelected(checkedInfo);
          setVisible(false);
        }}
      >
        <div className={styles.selected}>
          {
            checkedInfo.map(item => (
              <div key={item.userId} className={styles.selectItem}>
                <div className={styles.avatar}>{item.zhName[0]}</div>
                {item.zhName}
                <CloseOutlined className={styles.closeBtn} onClick={() => {
                  setDeleteKeys(item.userId);
                  setCheckedInfo(checkedInfo.filter(n => {
                    return n.userId !== item.userId
                  }));
                }} />
              </div>
            ))
          }
        </div>
        <Card
          className={styles.cardPanel}
          tabList={tabListNoTitle}
          activeTabKey={tabActive}
          tabBarExtraContent={
            <Input value={searchValue} prefix={<SearchOutlined />} placeholder="搜索" onChange={(e) => onSearch(e)} />
          }
          onTabChange={key => { setTabActive(key); setSearchValue(''); }}
        >
          <div className={styles.orgStaffPanel}>
            <Tree
              tabActive={tabActive}
              className={classnames(styles.treePanel, {
                [styles.orgWidthNull]: tabActive === 'staff'
              })}
              searchValue={searchValue}
              // ref={treeRef}
              data={orgTree}
              multiple={props.multiple}
              onSelect={(data) => {
                setSelectOrgKeys(data);
              }}
            />
            <Staff
              className={classnames(styles.staffBox, {
                [styles.radioStyle]: !props.multiple
              })}
              initData={okSelected}
              tabActive={tabActive}
              orgKeys={selectOrgKeys}
              searchValue={searchValue}
              deleteKeys={deleteKeys}
              multiple={props.multiple}
              onCheck={(items: StaffInfo[], type?: string) => {
                const multiple = props.multiple;
                if (type === 'add' && multiple) {
                  setCheckedInfo(checkedInfo.concat(items));
                } else if (type === 'del' && multiple) {
                  const delUserIds = items.map(item => item.userId);
                  setCheckedInfo(checkedInfo.filter(n => !delUserIds.includes(n.userId)));
                } else {
                  const getItem = checkedInfo.find(n => n.userId === items[0].userId);
                  if (getItem) {
                    setCheckedInfo(checkedInfo.filter(n => n.userId !== items[0].userId));
                  } else if (multiple) {
                    setCheckedInfo(checkedInfo.concat(items));
                  } else {
                    setCheckedInfo(items)
                  }
                }
              }} />
          </div>

        </Card>
      </Modal>
    </div>
  )
}

export default OrgStaff;
